setAutofillId

Sets the unique, logical identifier of this view in the activity, for autofill purposes.

The autofill id is created on demand, and this method should only be called when a view is reused after dispatchProvideAutofillStructure is called, as that method creates a snapshot of the view that is passed along to the autofill service.

This method is typically used when view subtrees are recycled to represent different content* —in this case, the autofill id can be saved before the view content is swapped out, and restored later when it's swapped back in. For example:

EditText reusableView = ...;
ViewGroup parentView = ...;
AutofillManager afm = ...;

// Swap out the view and change its contents
AutofillId oldId = reusableView.getAutofillId();
CharSequence oldText = reusableView.getText();
parentView.removeView(reusableView);
AutofillId newId = afm.getNextAutofillId();
reusableView.setText("New I am");
reusableView.setAutofillId(newId);
parentView.addView(reusableView);

// Later, swap the old content back in
parentView.removeView(reusableView);
reusableView.setAutofillId(oldId);
reusableView.setText(oldText);
parentView.addView(reusableView);

NOTE: If this view is a descendant of an android.widget.AdapterView, the system may reset its autofill id when this view is recycled. If the autofill ids need to be stable, they should be set again in getView. Compatibility behavior:

  • SDK 28 and above, this method matches platform behavior.
  • SDK 27 and below, this method does nothing.

Parameters

v

The View against which to invoke the method.

id

an autofill ID that is unique in the android.app.Activity hosting the view, or null to reset it. Usually it's an id previously allocated to another view (and obtained through getAutofillId), or a new value obtained through getNextAutofillId.

Throws

if the view is already attached to a window.

if the id is an autofill id associated with a virtual view.